<?php

namespace App\Admin\Controllers;

use App\Admin\Traits\tabMenu;
use App\Exports\MoneyOutExport;
use App\Models\Client;
use App\Models\CrmConfig;
use App\Models\Department;
use App\Models\MoneyOut;
use App\Models\User;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;

class MoneyOutController extends BaseController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '合同管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($client_id = 0)
    {
        $grid = new Grid(new MoneyOut());
        $users = User::Users();
        $grid->exporter(new MoneyOutExport());

        if($client_id > 0){
            $grid->model()->where('client_id',$client_id);
            $grid->disableCreateButton();
            $grid->disableColumnSelector();
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableActions();
        }
        $grid->model()
            ->with(['employee','client'])
            ->orderBy('created_at', 'desc');

        $grid = $this->permissions($grid, false, false, false,true,false);

        $grid->column('id',__('ID'))->sortable();
        $grid->column('sign_at','签约日期')->display(function ($model){return Carbon::parse($model)->toDateString();});
        $grid->column('client.name','姓名')->display(function ($model){
            return "<a href='/admin/clients/".$this->client->id."/edit'>$model</a>";
        });
        $grid->column('employee_id','所属销售员')->using($users);
        $grid->column('client.leader','上级主管')->display(function ($model){
            return Department::getLeader($this->employee_id);
        });

        $grid->column('employee.dep_l3','所属三级部门')->using(Department::getLevel(3));
        $grid->column('employee.dep_l2','所属二级部门')->using(Department::getLevel(2));
        $grid->column('employee.dep_l1','所属一级部门')->using(Department::getLevel(1));

        $grid->column('out_id','产品');

        $grid->column('client.employee_status','销售跟进状态')->editable('select', CrmConfig::getKeyValue('follow_status'));
        $grid->column('check_status','权证跟进状态')->editable('select', CrmConfig::getKeyValue('quanzheng_status'));
        $grid->column('client.oneLastRecords.records','最新跟进记录');
        $grid->column('client.status','客户类型')->using(CrmConfig::getKeyValue('client_status'));

        self::newestRecords($grid);
        $grid->column('foo','未跟进天数')->display(function ($model){
            $nt = (int) ceil((time() - strtotime($this->client->oneLastRecords->created_at)) / 60 / 60 / 24);
            return $nt > 3650 ? '从未' : $nt;
        });

        $grid->column('quanzheng_id','权证人')->using($users);

        $grid->filter(function ($filter) use ($users){
//            self::filter($filter);
            $filter->columen(1/3, function (Grid\Filter $filter){
                $filter->equal('check_status','权证跟进状态')->select(CrmConfig::getKeyValue('quanzheng_status'));
                $filter->equal('quanzheng_id','权证人')->select(User::Users());
                $filter->equal('employee.dep_l3','所属三级部门')->select(Department::getLevel(3));
            });
            $filter->columen(1/3, function (Grid\Filter $filter){
                $filter->like('name','客户姓名');
                $filter->between('sign_at','签约日期')->date();
                $filter->equal('employee.dep_l1','所属一级部门')->select(Department::getLevel(1));
            });
            $filter->columen(1/3, function (Grid\Filter $filter) use ($users){
                $filter->equal('employee_id','所属销售员')->select($users);
                $filter->equal('employee.dep_l2','所属二级部门')->select(Department::getLevel(2));
            });

        });
        return $grid;
    }

    public function show($client_id, Content $content)
    {
        $client_name = Client::getAllClients()[$client_id];
        $content
            ->title($this->title().' - '.$client_name)
            ->description($this->description['show'] ?? trans('admin.show'))
            ->row(function ($row) use ($client_id){
                $row->column(12, tabMenu::tabMenuList($client_id));
            })
            ->row(function ($row) use ($client_id){
                $row->column(6, $this->grid($client_id));
                $row->column(6, $this->form($client_id));
            });
        return $content;
    }


    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(MoneyOut::findOrFail($id));

        $show->field('id', __('ID'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($client_id=0)
    {
        $form = new Form(new MoneyOut);

        // 销售的正常逻辑
        if(Admin::user()->isRole('employee')) {
            $form->hidden('employee_id', '所属销售员')->default(Admin::user()->id);
        }

        $client_name = $client_id > 0 ? Client::getAllClients()[$client_id] : '';
        if($client_id == 0){
            $form->select('client_id', '客户姓名')->options(Client::getAllClients());
        }else{
            $form->hidden('client_id', '客户id')->value($client_id);
            $form->text('client_name', '客户姓名')->value($client_name)->disable();
        }

        $form->textarea('out_id','放贷产品')->required();
        $form->currency('out_money','批款金额（万）')->symbol("￥")->required();
        $form->currency('out_count','批款笔数')->symbol("￥")->required();
        $form->currency('real_money','放贷金额（万）')->symbol("￥")->required();
        $form->currency('fee','居间服务费（¥）：')->symbol("￥");
        $form->date('out_at','放贷日期');

        $form->select('pay_type','还款方式')->options(CrmConfig::getKeyValue('money_back_type'));
        $form->number('pay_count','期数');
        $form->currency('pay_monthly','月还款金额')->symbol('￥');
        $form->date('back_at','放贷日期');
        $form->textarea('note','备注');

        if(Admin::user()->isRole('quanzheng'))
        {
            $form->select('quanzheng_id', '权证人')->options(User::Users())->default(Admin::user()->id);
            $form->select('check_status', '权证跟进状态')->options(CrmConfig::getKeyValue('quanzheng_status'));
        }else{
            $form->select('quanzheng_id', '权证人')->options(User::Users());
            $form->select('check_status', '权证跟进状态')->options(CrmConfig::getKeyValue('quanzheng_status'))->default(1);
        }

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
            $tools->disableList();
        });
        $form->disableEditingCheck();
        $form->disableCreatingCheck();
        $form->disableViewCheck();
        if($client_id == 0){
            $form->saving(function (Form $form){
                if(isset($form->client_id)){
                    $clientModel = Client::query()->where('id',$form->client_id)->first();
                    $form->client_name = $clientModel->name;
                    $form->mobile = $clientModel->mobile;
                }
            });
        }else{
            $form->saved(function (Form $form) use ($client_id){
                return back();
            });
        }


        return $form;
    }
}
